package pro.uccs.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

/*
 * AES对称加密和解密
 */
public class SymmetricEncoder {
	/*
	 * 加密
	 * 1.构造密钥生成器
	 * 2.根据ecnodeRules规则初始化密钥生成器
	 * 3.产生密钥
	 * 4.创建和初始化密码器
	 * 5.内容加密
	 * 6.返回字符串
	 */
	public static String AESEncode(String encodeRules, String content) {
		try {
			//1.构造密钥生成器，指定为AES算法,不区分大小写
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			//2.根据ecnodeRules规则初始化密钥生成器
			//生成一个128位的随机源,根据传入的字节数组
			keygen.init(128, new SecureRandom(encodeRules.getBytes()));
			//3.产生原始对称密钥
			SecretKey original_key = keygen.generateKey();
			//4.获得原始对称密钥的字节数组
			byte[] raw = original_key.getEncoded();

			//5.根据字节数组生成AES密钥
			SecretKey key = new SecretKeySpec(raw, "AES");
			//6.根据指定算法AES自成密码器
			Cipher cipher = Cipher.getInstance("AES");
			//7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
			cipher.init(Cipher.ENCRYPT_MODE, key);
			//8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
			byte[] byte_encode = content.getBytes("utf-8");
			//9.根据密码器的初始化方式--加密：将数据加密
			byte[] byte_AES = cipher.doFinal(byte_encode);
			//10.将加密后的数据转换为字符串
			//这里用Base64Encoder中会找不到包
			//解决办法：
			//在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
			String AES_encode = new String(new BASE64Encoder().encode(byte_AES));
			//11.将字符串返回
			return AES_encode;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//如果有错就返加nulll
		return null;
	}

	/**
	 * 16位秘钥加密
	 *
	 * @param key     秘钥
	 * @param Content
	 * @return
	 */
	public static String encrypt(String key, String Content) {
		try {
			if (key.length() != 16) {
				throw new Exception("秘钥key的长度必须为16");
			}
			byte[] byte_encode = null;
			SecretKeySpec skey = new SecretKeySpec(key.getBytes("utf-8"), "AES");
			//IvParameterSpec ivspec = new IvParameterSpec(key.getBytes("utf-8"));
			//Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");	  
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, skey);
			byte_encode = cipher.doFinal(Content.getBytes());
			return new String(new BASE64Encoder().encode(byte_encode));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 16位秘钥解密
	 *
	 * @param key
	 * @param content
	 * @return
	 */
	public static String decrypt(String key, String content) {
		try {
			if (key.length() != 16) {
				throw new Exception("秘钥key的长度必须为16");
			}
			byte[] output = null;
			SecretKeySpec skey = new SecretKeySpec(key.getBytes("utf-8"), "AES");

			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skey);
			output = cipher.doFinal(new BASE64Decoder().decodeBuffer(content));
			return new String(output);
		} catch (Exception e) {
			e.printStackTrace();
			;
		}
		return null;
	}


	/*
	 * 解密
	 * 解密过程：
	 * 1.同加密1-4步
	 * 2.将加密后的字符串反纺成byte[]数组
	 * 3.将加密内容解密
	 */
	public static String AESDecode(String encodeRules, String content) {
		try {
			//1.构造密钥生成器，指定为AES算法,不区分大小写
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			//2.根据ecnodeRules规则初始化密钥生成器
			//生成一个128位的随机源,根据传入的字节数组
			keygen.init(128, new SecureRandom(encodeRules.getBytes()));
			//3.产生原始对称密钥
			SecretKey original_key = keygen.generateKey();
			//4.获得原始对称密钥的字节数组
			byte[] raw = original_key.getEncoded();

			System.out.println(Bytes2hexStr(raw));
			//5.根据字节数组生成AES密钥
			SecretKey key = new SecretKeySpec(raw, "AES");
			//6.根据指定算法AES自成密码器
			Cipher cipher = Cipher.getInstance("AES");
			//7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
			cipher.init(Cipher.DECRYPT_MODE, key);
			//8.将加密并编码后的内容解码成字节数组
			byte[] byte_content = new BASE64Decoder().decodeBuffer(content);


			byte[] byte_decode = cipher.doFinal(byte_content);
			String AES_decode = new String(byte_decode, "utf-8");
			return AES_decode;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		//如果有错就返加nulll
		return null;
	}

	public static String getMD5(String str) {
		try {
			// 生成一个MD5加密计算摘要
			MessageDigest md = MessageDigest.getInstance("MD5");
			// 计算md5函数
			md.update(str.getBytes());
			// digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
			// BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
			return new BigInteger(1, md.digest()).toString(16);
		} catch (Exception e) {

		}
		return null;
	}

	public static String Bytes2hexStr(byte[] b) {
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < b.length; i++) {
			stmp = Integer.toHexString(b[i] & 0xFF);
			sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
		}

		return sb.toString().toUpperCase().trim();
	}


	public static String byteToHexString(byte[] b) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexString.append(hex.toUpperCase());
		}
		return hexString.toString();
	}
}
